package com.example.tool.service;

import cn.hutool.core.util.ObjectUtil;
import com.example.tool.bean.business.wdt.SelfOrderDO;
import com.example.tool.util.DateUtil;
import com.example.tool.util.ExpressDeliveryUtil.ExpressDeliveryResult;
import com.example.tool.util.ExpressDeliveryUtil.ExpressDeliveryTrack;
import com.example.tool.util.ExpressDeliveryUtil.ExpressDeliveryUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.example.tool.conf.WarehouseMsgConfig.collectionDelayKeyTemplate;
import static com.example.tool.conf.WarehouseMsgConfig.transferTimeoutAfterKeyTemplate;
import static com.example.tool.conf.WarehouseMsgConfig.transferTimeoutKeyTemplate;
import static com.example.tool.util.ExpressDeliveryUtil.TrackTypeEnum.RECEIVED;

@Service
public class AsyncService {
    private static AsyncService instance;
    @PostConstruct
    public void init() {
        instance = this;
    }
    @Autowired
    private RedisService redisService;

    /**
     * @param orders
     */
    @Async
    public String  setCollectionDelay(SelfOrderDO orders) {
//        List<Integer>sendStatus=Arrays.asList(95, 96, 101, 110);
        ExpressDeliveryResult result = ExpressDeliveryUtil.queryLogistics(orders.getLogisticsNo());
        String scanType = "";
        if (result.getSucceed()){
            Date now = new Date();
            List<ExpressDeliveryTrack> tracks = result.getTracks();
            if (tracks.isEmpty()){
                /**
                 * 0 发货后24小时未揽收=虚假发货
                 * 1 揽收后24小时未更新中转=虚假揽收
                 * 2 揽收后及时更新中转后24小时未更新下一条物流信息（做提醒），超48小时算丢件还会有赔付 -有揽无发
                 */
//        if(!sendStatus.contains(orders.getTradeStatus())){
                Date consignTime = orders.getConsignTime();
                if (ObjectUtil.isNotNull(consignTime)){
                    Date outTime = DateUtil.addHourDate(consignTime, 24);
                    long timeDifference = DateUtil.findTimeDifference(now, outTime);
                    if (timeDifference>0){
                        redisService.setWithExpire( String.format(collectionDelayKeyTemplate,orders.getLogisticsNo()),"",timeDifference, TimeUnit.SECONDS);
                    }
                }
//        }
            }else {
                scanType=tracks.get(tracks.size()-1).getScanType();
                int size = tracks.size();
                String KeyTemplate="";
                //是否到过中转站
                boolean b = tracks.stream().noneMatch(e -> e.getIsTransfer() && ObjectUtil.equal(e.getScanType(), RECEIVED.getCode()));
                if (b){
                    KeyTemplate=transferTimeoutAfterKeyTemplate;
                }else {
                    KeyTemplate=transferTimeoutKeyTemplate;
                }
                Date scanDate = tracks.get(size-1).getScanDate();
                Date outTime = DateUtil.addHourDate(scanDate, 24);
                long timeDifference = DateUtil.findTimeDifference(now, outTime);
                if(timeDifference>0){
                redisService.setWithExpire(String.format(KeyTemplate,orders.getLogisticsNo()),"",timeDifference, TimeUnit.SECONDS);
                }

            }
        }
         return scanType;
    }

    public static String setCollectionDelayStatic(SelfOrderDO orders) {
        if (instance == null) {
            throw new IllegalStateException("AsyncService instance not initialized");
        }
        return instance.setCollectionDelay(orders);
    }

    public static String findPrefix(String key){
        return key.substring(0,key.lastIndexOf(":"));
    }


}
